#===============================================
# Code written by Joe France (joeprogram.com)
# Released under code.google.com/p/video-scholar/
# with the MIT license (aka, the do-whatever-you-want-with-it license)
#===============================================

from lxml import etree
import mimetypes
import os
import pyglet
from pyglet.window import key
import Tkinter
import tkFileDialog

from HotKey import HotKey
from State import State
from Timeline import Timeline
from VideoPlayer import VideoPlayer

class MainState( State ):
	'''
	Main State is the screen where the meat of the application lives
	'''

	HOTKEY_X = 600
	HOTKEY_Y = 416
	HOTKEY_SPACE = 50

	def __init__( self, app, file_path):
	
		super(MainState, self).__init__(app)
		
		save = None
		
		mimetype = mimetypes.guess_type( file_path )[0]
		if True:
		#if mimetype in ["video/x-msvideo", "video/mp4", "video/x-ms-wmv" ]:
		
			self.video_path = file_path
			xml_path = os.path.splitext( self.video_path )[0] + ".xml"
			if os.path.exists( xml_path ):
				save = self.open_xml(xml_path )
		
		elif mimetype == "text/xml":
		
			save = self.open_xml( file_path )
			self.video_path = save.find('video').get('path')
		
		else:
			raise Exception("PROBLEM: You've selected an unsupported file type %s.  SOLUTION: Please use a video file or an xml file." % mimetype)
		
		
		self.video_player = VideoPlayer( self.video_path )
		self.guis.append( self.video_player )				
				
		self.timeline = Timeline( self )
		self.timeline.set_context( self.video_player )
		self.guis.append( self.timeline )
		
		self.hot_keys = []
		
		if save:
			self.import_xml( save )
		else:
			hot_key = HotKey( key = key.F )
			self.hot_keys.append( hot_key )
			self.timeline.register_hot_key( hot_key )
			self.position_hot_keys()
			
		self.guis += self.hot_keys

	def open_xml( self, xml_path ):
		'''
		Opens the xml file
		Either returning a etree node if everything went ok
		Or None if there was an error
		'''
		
		try:
			return etree.parse( xml_path )
		except etree.XMLSyntaxError, e:
			if e.msg.startswith( "Document is empty"):
				print "WARNING: I tried to open the XML file %s, but that file is blank. SOLUTION: You can keep going - I'll overwrite the blank file when you save." % xml_path
			else:
				print 'WARNING: I Tried to open the XML file %s, but I recieved the error "%s".  SOLUTION: Open the xml file, and ensure it is properly formatted xml.' % (xml_path, e )
			return None

	def import_xml( self, node ):
		'''
		Read an xml file associated with a video
		Pass it along to any other objects who need to be setup from it
		'''
		for hot_key_node in node.findall('hot_key'):
			self.hot_keys.append( HotKey.create_from_xml( hot_key_node ) )
		
		self.timeline.import_xml( node )
		self.position_hot_keys()
		
		
	def export_xml( self, node ):
		'''
		Export everything to an xml tree
		'''
		
		etree.SubElement(node,'save').set('version',str( self.app.get_version()) )
		video_node = etree.SubElement( node, 'video')
		video_node.set('path',self.video_path )
						
		for hot_key in self.hot_keys:
			hot_key.export_xml( node )
						
		self.timeline.export_xml( node )
		
	def get_hot_keys( self ):
		return self.hot_keys
		
	def get_hot_key( self, key ):
		'''
		Given the keyboard key,
		Return the corresponding hotkey
		'''
		
		key = int( key )
		
		for hot_key in self.hot_keys:
			if hot_key.key == key:
				return hot_key
				
	def position_hot_keys( self ):
		'''
		Rearranges all the positions of the hotkeys
		Call after you make a new HotKey
		'''
		
		for i, hot_key in enumerate(self.hot_keys):
		
			hot_key.set_coordinates( x = self.HOTKEY_X, y = self.HOTKEY_Y - i * self.HOTKEY_SPACE )
		
	def key_press( self, symbol, modifiers ):
		'''
		First we'll check for any special commands
		Like Saving or Opening
		If we don't find any of those,
		we'll pass the keypresses onto the children GUIs
		'''
		
		# Save the Video
		if key.MOD_CTRL & modifiers and symbol == key.S:
			print "Saving..."
			self.save()
			
		# Load a New Video
		elif key.MOD_CTRL & modifiers and symbol == key.O:
			self.video_player.start_action( VideoPlayer.PAUSE )
			self.load_video()
			self.video_player.end_action()
			
		# Pass the keypress onto the Children GUI	
		else:

			for hot_key in self.hot_keys:
				hot_key.key_press( symbol, modifiers )
			self.video_player.key_press( symbol, modifiers )
		
	def save( self ):
		'''
		Save an xml file
		
		XML will be the main format of save files
		We could make the files a little smaller with a binary format,
		but one of the goals of Video Scholar is ease of use.
		This way, a user who is familiar with XML can do whatever they want 
		with their own data file.
		'''
	
		root = Tkinter.Tk()
		root.withdraw()				
		file = open(os.path.splitext( self.video_path )[0] + ".xml", 'w')
		
		root = etree.Element('video_scholar_save')
		self.export_xml( root )
		
		file.write( etree.tostring( root, pretty_print = True ))
		file.close()
		

		
		
		
		

